from django.db import models

# Create your models here.

from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse # 导入reverse函数

from taggit.managers import TaggableManager #导入标签管理器



# 类名'PublishedManager'为自拟名称，该类继承自models.Manager
class PublishedManager(models.Manager):
  #重写Manager父类的get_queryset方法
  def get_queryset(self):
    #通过super()调用父类get_queryset()方法获取所有文章再调用过滤方法filter，获得已经发布的文章
    return super(PublishedManager,self).get_queryset().filter(status='published')

class Post(models.Model):
 # 重新创建初始模型管理器，确保初始模型管理器可用
 objects = models.Manager()
 # 使用自定义模型管理器 PublishedManager 类创建一个管理器实例
 published = PublishedManager()#把定义的类实例化
 #增加tags字段
 tags = TaggableManager()
 STATUS_CHOICES=(
 ('draft','Draft'),
 ('published','Published')
 )
 
#reverse函数可以根据路由名称反向生成路由，第一个参数是路由名称，
#第二个参数是路由需要的参数
 def get_absolute_url(self):
   return reverse('blog:post_detail',args=[self.publish.year,self.publish.month,self.publish.day,self.slug])

 title = models.CharField(max_length=250)
 body = models.TextField()
 slug = models.SlugField(max_length=250,unique_for_date='publish')
 author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='author')
 publish = models.DateTimeField(default=timezone.now)
 created = models.DateTimeField(auto_now_add=True)
 updated = models.DateTimeField(auto_now=True)
 status = models.CharField(max_length=10,choices=STATUS_CHOICES, default='draft')
 class Meta:
   ordering=('-publish',)
 def __str__(self):
   return self.title                                                                        

#添加评论数据模型类
class Comment(models.Model):
  post=models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
  name = models.CharField(max_length=80)
  email = models.EmailField()
  body = models.TextField()
  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)
  active = models.BooleanField(default=True)
  class Meta:
    ordering = ('created',)
  def __str__(self):
    return f'Comment by {self.name} on {self.post}'
